package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.domain.TbUser;
import com.bwie.mapper.TbUserMapper;
import com.bwie.service.TbUserService;
import com.bwie.utils.R;
import com.bwie.vo.LoginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2024/11/2 11:54
 */

@Service
public class TbUserServiceImpl implements TbUserService {

    @Autowired
    TbUserMapper tbUserMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public R login(LoginInfoVo loginInfoVo) {
        //-- 根据手机号查询用户
        TbUser tbUser = tbUserMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserMobile, loginInfoVo.getUserMobile())
        );
        if (tbUser == null) {
            return R.ERROR(404, "用户不存在");
        }

        //-- 校验密码（不加密的密码比较）
        if (!tbUser.getUserPass().equals(loginInfoVo.getUserPass())) {
            return R.ERROR(500, "密码错误");
        }

        //-- 生成token并存储到 redis
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("userName", tbUser.getUserName())
                .compact();

        // token过期时间设为60分钟
        String tokenKey = "token-" + tbUser.getUserId();
        stringRedisTemplate.opsForValue().set(tokenKey, token, 60, TimeUnit.MINUTES);

        tbUser.setToken(token);
        tbUser.setUserPass(null);

        return R.OK(tbUser);
    }

    @Override
    public R getUserById(Integer userId) {
        TbUser tbUser = tbUserMapper.selectById(userId);
        if(tbUser == null) {
            return R.ERROR(404, "用户不存在");
        }
        return R.OK(tbUser);
    }
}
